// 加载环境变量
require('dotenv').config();

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const path = require('path');

// 导入配置
const { sequelize, syncConfig } = require('./src/config/database');

// 导入中间件
const { errorHandler } = require('./src/middleware/errorHandler');

// 导入路由
const authRoutes = require('./src/routes/auth');
const userRoutes = require('./src/routes/user');
const courseRoutes = require('./src/routes/course');
const adminRoutes = require('./src/routes/admin');
const teacherRoutes = require('./src/routes/teacher');
const studentRoutes = require('./src/routes/student');
const studentCourseRoutes = require('./src/routes/student-course');

const paymentRoutes = require('./src/routes/payment');
const uploadRoutes = require('./src/routes/upload');
const notificationRoutes = require('./src/routes/notification');
const statisticsRoutes = require('./src/routes/statistics');
const docsRoutes = require('./src/routes/docs');
const lessonRoutes = require('./src/routes/lesson');

// 导入模型关联
require('./src/models/index');



const app = express();
const PORT = process.env.PORT || 3000;

// 安全中间件
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"],
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", "data:", "https:"],
    },
  },
}));

// 压缩中间件
app.use(compression());

// CORS配置
const corsOptions = {
  origin: '*', // 允许所有域名访问，生产环境应改为你的前端域名
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true, // 允许携带 cookie 等凭证
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP 15分钟内最多100个请求
  message: {
    code: 429,
    message: '请求过于频繁，请稍后再试'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

app.use('/api/', limiter);

// 更严格的API速率限制
const apiLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 50,
  message: {
    code: 429,
    message: 'API请求过于频繁，请稍后再试'
  }
});

app.use('/api/auth/', apiLimiter);

// 解析请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/upload', express.static(path.join(__dirname, 'public/upload')));

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'ok',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development'
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/user', userRoutes);
app.use('/api/course', courseRoutes);
app.use('/api/courses', courseRoutes); // 添加复数形式的路由
app.use('/api/admin', adminRoutes);
app.use('/api/teacher', teacherRoutes);
app.use('/api/student', studentRoutes);
app.use('/api/student-course', studentCourseRoutes);

app.use('/api/payment', paymentRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/notification', notificationRoutes);
app.use('/api/statistics', statisticsRoutes);
app.use('/api/docs', docsRoutes);
app.use('/api/lesson', lessonRoutes);

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '思研社平台 API',
    version: '1.0.0',
    documentation: '/api/docs',
    health: '/health'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在'
  });
});

// 错误处理中间件
app.use(errorHandler);

// 数据库连接和服务器启动
async function startServer() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');

    // 同步数据库模型
    if (syncConfig.enableSync) {
      console.log('🔄 开始同步数据库模型...');
      console.log(`📋 同步模式: ${syncConfig.syncMode}`);
      
      try {
        if (syncConfig.syncMode === 'force') {
          await sequelize.sync({ force: true, logging: syncConfig.syncLogging });
          console.log('✅ 数据库模型强制同步完成（表已重新创建）');
        } else if (syncConfig.syncMode === 'alter') {
          await sequelize.sync({ alter: true, logging: syncConfig.syncLogging });
          console.log('✅ 数据库模型同步完成（表结构已更新）');
        } else {
          console.log('ℹ️ 跳过数据库同步');
        }
      } catch (error) {
        console.error('❌ 数据库同步失败:', error.message);
        if (process.env.NODE_ENV === 'production') {
          console.error('生产环境中数据库同步失败，服务器将退出');
          process.exit(1);
        } else {
          console.warn('⚠️ 开发环境中继续启动服务器');
        }
      }
    } else {
      console.log('ℹ️ 数据库同步已禁用');
    }



    // 启动HTTP服务器
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`🚀 服务器启动成功`);
      console.log(`📍 端口: ${PORT}`);
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`📚 API文档: http://localhost:${PORT}/api/docs`);
    });



  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
}

// 优雅关闭
process.on('SIGTERM', async () => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  
  try {
    await sequelize.close();
    console.log('✅ 数据库连接已关闭');
    process.exit(0);
  } catch (error) {
    console.error('❌ 关闭数据库连接时出错:', error);
    process.exit(1);
  }
});

process.on('SIGINT', async () => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  
  try {
    await sequelize.close();
    console.log('✅ 数据库连接已关闭');
    process.exit(0);
  } catch (error) {
    console.error('❌ 关闭数据库连接时出错:', error);
    process.exit(1);
  }
});

// 启动服务器
startServer();

module.exports = app; 